package com.gnerv.rabbitmq.agent.handler;

import com.gnerv.rabbitmq.agent.tools.ExecTools;
import com.google.common.collect.Maps;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Gnerv LiGen
 */
@Slf4j
@Data
public abstract class ExecResultHandler<T> {

    private String version;
    private ExecTools.ExecResult execResult;

    public abstract T handle();

    protected final Map<Integer, String> matcher(String regex, int... group) {
        Map<Integer, String> result = Maps.newHashMap();
        Pattern pattern = Pattern.compile(regex);
        return getMatcherResult(pattern, result, group);
    }

    protected final Map<Integer, String> matcher(Pattern pattern, int... group) {
        Map<Integer, String> result = Maps.newHashMap();
        return getMatcherResult(pattern, result, group);
    }

    private Map<Integer, String> getMatcherResult(Pattern pattern, Map<Integer, String> result, int[] group) {
        Matcher matcher = pattern.matcher(execResult.getStdout());
        boolean matches = matcher.find();
        if (matches) {
            for (int i : group) {
                result.put(i, matcher.group(i));
            }
        } else {
            log.error("没有匹配到 " + pattern.pattern());
        }
        return result;
    }

}
